<?php

namespace GuanChanghu\Library\Models;

use GuanChanghu\Exceptions\UserException;
use GuanChanghu\Utils\Time\Facade as TimeUtil;
use Exception;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

/**
 * @author 管昌虎
 * Class FileStoreRecord
 * @tag encryption free
 * @package GuanChanghu\Library\Models
 * Created on 2022/2/28 8:43
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 */
class FileStoreRecord extends \GuanChanghu\Models\Model
{
    /**
     * 状态-显示
     */
    public const STATUS_SHOW = 1;

    /**
     * 状态-不显示
     */
    public const STATUS_BLANK = 0;

    /**
     * 数值精度处理
     *
     * @var string[]
     */
    protected $casts = [
        'user_id' => 'integer',
        'client' => 'string',
        'module' => 'string',
        'type' => 'string',
        'extension' => 'string',
        'relative' => 'string',
        'path' => 'string',
        'original_file_name' => 'string',
        'size' => 'integer',
        'status' => 'integer',
    ];

    /**
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(config('guan-changhu.models.user'), 'user_id');
    }

    /**
     * @param array $data
     * @return FileStoreRecord
     * @throws Exception
     */
    public static function store(array $data): static
    {
        static::fileExists($data['relative'], $data['originalFileName'], $data['type'], $data['extension']);

        return static::initialize($data)->changes();
    }


    /**
     * 验证一定时间内是不是存在相同文件
     * @param string $relative
     * @param string $originalFileName
     * @param string $type
     * @param string $extension
     * @param int $minute
     * @return bool
     * @throws UserException
     * @throws Exception
     */
    private static function fileExists(string $relative, string $originalFileName, string $type, string $extension, int $minute = 60): bool
    {
        $fileSize = Storage::size($relative);

        $exists = static::query()
            ->where('type', $type)
            ->where('extension', $extension)
            ->where('original_file_name', $originalFileName)
            ->where('size', $fileSize)
            ->where(static::CREATED_AT, '>=', TimeUtil::getSubMillisecondTimestamp($minute))
            ->exists();

        if ($exists) {
            Storage::delete($relative);

            throw new UserException(__('guan-changhu::upload.file_exist'));
        }

        return false;
    }
}
